// admin/system/service/sys_dict_type_service.go
package service

import (
	"errors"
	repo "go-admin1/admin/system/dao"
	"go-admin1/admin/system/model"
)

// SysDictTypeService 字典类型服务接口
type SysDictTypeService interface {
	Create(dictType *model.SysDictType) error
	GetByID(id int64) (*model.SysDictType, error)
	GetByDictType(dictType string) (*model.SysDictType, error)
	Update(dictType *model.SysDictType) error
	Delete(id int64) error
	List(page, pageSize int) ([]*model.SysDictType, int64, error)
	ListAll() ([]*model.SysDictType, error)
}

type sysDictTypeService struct {
	dictTypeDao repo.SysDictTypeDao
}

func (s sysDictTypeService) Create(dictType *model.SysDictType) error {
	return s.dictTypeDao.Create(dictType)
}

func (s sysDictTypeService) GetByID(id int64) (*model.SysDictType, error) {
	dictType, err := s.dictTypeDao.GetByID(id)
	if err != nil {
		return nil, err
	}
	return dictType, nil
}

func (s sysDictTypeService) GetByDictType(dictType string) (*model.SysDictType, error) {
	dict, err := s.dictTypeDao.GetByDictType(dictType)
	if err != nil {
		return nil, err
	}
	return dict, nil
}

func (s sysDictTypeService) Update(dictType *model.SysDictType) error {
	existingDictType, err := s.dictTypeDao.GetByID(dictType.DictID)
	if err != nil {
		return err
	}
	if existingDictType == nil {
		return errors.New("字典类型不存在")
	}

	return s.dictTypeDao.Update(dictType)
}

func (s sysDictTypeService) Delete(id int64) error {
	existingDictType, err := s.dictTypeDao.GetByID(id)
	if err != nil {
		return err
	}
	if existingDictType == nil {
		return errors.New("字典类型不存在")
	}

	return s.dictTypeDao.Delete(id)
}

func (s sysDictTypeService) List(page, pageSize int) ([]*model.SysDictType, int64, error) {
	dictTypes, total, err := s.dictTypeDao.List(page, pageSize)
	if err != nil {
		return nil, 0, err
	}
	return dictTypes, total, nil
}

func (s sysDictTypeService) ListAll() ([]*model.SysDictType, error) {
	dictTypes, err := s.dictTypeDao.ListAll()
	if err != nil {
		return nil, err
	}
	return dictTypes, nil
}

// NewSysDictTypeService 创建字典类型服务实例
func NewSysDictTypeService() SysDictTypeService {
	return &sysDictTypeService{
		dictTypeDao: repo.NewSysDictTypeDao(),
	}
}
